package com.javaee.option_system.interceptor;

import com.javaee.option_system.enums.ExceptionEnums;
import com.javaee.option_system.exception.MyException;
import com.javaee.option_system.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class StudentInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token==null || "".equals(token)) {
            throw new MyException(ExceptionEnums.NO_PERMISSIONS);
        }
        Claims claims ;
        try {
            claims = jwtUtil.parseJWT(token);
        } catch (Exception e) {
            throw new MyException(ExceptionEnums.TOKEN_TIME_OUT);
        }
        if (!claims.get("roles").equals("student")){
            throw new MyException(ExceptionEnums.NO_PERMISSIONS);
        }
        return true;
    }
}
